package com.skyworthclub.competition.controller;


import com.baomidou.mybatisplus.plugins.Page;
import com.skyworthclub.competition.beans.Feedback;
import com.skyworthclub.competition.service.FeedbackService;
import com.skyworthclub.competition.utils.web.DataValidateUtil;
import com.skyworthclub.competition.utils.web.ResponseUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.*;

import org.springframework.stereotype.Controller;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 反馈前端控制器
 * </p>
 *
 * @author li
 * @since 2018-10-15
 */
@Controller
@RequestMapping("/api/feedback")
public class FeedbackController {

    private final FeedbackService feedbackService;

    @Autowired
    public FeedbackController(FeedbackService feedbackService) {
        this.feedbackService = feedbackService;
    }

    @PostMapping("/post")
    public ResponseEntity<Map<String, Object>> addFeedback(@RequestBody @Valid Feedback feedback,
                                                           Errors errors) {
        Map<String, Object> map = new HashMap<>(4);
        //数据校验
        ResponseEntity<Map<String, Object>> responseEntity = DataValidateUtil.validate(errors);
        if (responseEntity != null) {
            return responseEntity;
        }

        boolean insert = feedbackService.insertAndNotice(feedback);
        if (insert) {
            map.put("status", 200);
            map.put("message", "反馈成功");
            return new ResponseEntity<>(map, HttpStatus.OK);
        } else {
            map.put("status", 400);
            map.put("message", "反馈失败");
            return new ResponseEntity<>(map, HttpStatus.OK);
        }
    }

    @GetMapping("/list/{pageNum}")
    public ResponseEntity<Map<String, Object>> listFeedBack(@PathVariable(value = "pageNum") Integer pageNum,
                                                            HttpServletRequest request) {

        String username = request.getUserPrincipal().getName();
        Map<String, Object> map = new HashMap<>(4);
        Page<Feedback> page = feedbackService.selectUserFeedbackPage(username, pageNum);
        map.put("feedbackPage", page);
        return ResponseUtil.querySuccessResponse(map);
    }

    @DeleteMapping("/delete/{feedbackId}")
    public ResponseEntity<Map<String, Object>> deleteFeedback(@PathVariable Integer feedbackId) {
        HashMap<String, Object> map = new HashMap<>(4);
        boolean delete = feedbackService.deleteById(feedbackId);
        if (delete) {
            return ResponseUtil.deleteSuccessResponse(map);
        } else {
            return ResponseUtil.deleteFailureResponse(map);
        }
    }
}

